<?php
namespace User\Controller;

use Think\Page;
use User\Controller\UserController;

/**
*
*/
class ZJDailyCardController extends UserController
{

	public function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
        $where['status'] = I( "status", 3, "" );
        $where['distributionyear'] = I( "distributionyear", date("Y") + 1, "" );
        if( $where['status'] == 3 ){
            $where['status'] = array( 'gt', 0 );
        }
        trace( "debug zjdailycard index 1", "zjdailycard", "SQL" );

        $card = D('zjrb_card');
        $count = $card->where($where)->count();

        $page = new Page($count, 15);
        $page->parameter['status'] = $where['status'];
        $page->parameter['distributionyear'] = $where['distributionyear'];
        $show = $page->show();

        $list = $card->field('card.id, cardnumber, signtime, status, distributionyear, cusAddr.username as username, cusAddr.telephone, a.regionname as city, b.regionname as county, address, cusAddr.metier as metier')
             ->alias('card')
             ->join('LEFT JOIN esm_zjdailycard_customer as cus ON card.customer_id = cus.id')
             ->join('LEFT JOIN esm_customer_addr as cusAddr ON card.addr_id = cusAddr.id')
             ->join('LEFT JOIN esm_region as a ON cusAddr.city = a.id')
             ->join('LEFT JOIN esm_region as b ON cusAddr.county = b.id')
             ->where($where)
            ->order( 'signtime desc,id' )
             ->limit($page->firstRow.','.$page->listRows)
             ->select();

        $this->assign( "page", $show );
		$this->assign('list', $list);
		$this->assign('search', $where);
        $this->display();
	}

    /**
     *（批量）删除报卡
     *@return 0：失败；1：成功。
     */
	public function delete()
	{
        $items = I( "post.items", array(), "" );
        $result = array( "error" => 404, "msg" => "" );
        if( !is_array( $items ) || !count( $items ) ){
            $result['error'] = 404;
            $this->ajaxReturn( $result );
        }
        $condition['id'] = array( 'in', $items );
        $deleted = M( 'zjrb_card' )->where( $condition )->setField( 'status', -2 );
        if( $deleted === false ){
            $result['error'] = 500;
            $this->ajaxReturn( $result );
        }else if( $deleted === 0 ){
            $result['error'] = 404;
            $this->ajaxReturn( $result );
        }else if( $deleted > 0 ){
            $result['error'] = 200;
            $this->ajaxReturn( $result );
        }
	}

    public function edit()
    {
        $condition = array();
        $id = I( "id", "", "" );
        if( empty( $id ) ){
            return $this->error( "没有此卡片" );
        }else{
            $condition['id'] = $id;
        }
        $card = M( 'zjrb_card' )->where( $condition )->find();

        /*$customer = array();
        if( !!$card['customer_id'] ){
            $condition = array( 'id' => $card['customer_id'] );
            $customer = M( 'zjdailycard_customer' )->where( $condition )->find();
        }*/

        $addr = array();
        if( !!$card['addr_id'] ){
            $condition = array( 'id' => $card['addr_id'], 'scope' => 'zjdailycard' );
            $addr = M( 'customer_addr' )->where( $condition )->find();
        }

        $this->assign( "card", $card );
        // $this->assign( "customer", $customer );
        $this->assign( "addr", $addr );
        $this->display();
    }

    public function update()
    {
        $data = I( "post.", array(), "" );
        $condition = array( 'id' => $data['id'], 'status' => array( 'gt', 0 ) );
        if( !$condition['id'] ){
            return $this->error( "更新失败" );
        }

        /*$updated_card = $this->updateZJDailyCard( $data, $condition );
        if( is_string( $updated_card ) ){
            return $this->error( $updated_card );
        }else if( $updated_card === false ){
            return $this->error( "卡片信息更新失败" );
        }*/

        // $customer_addr = M( 'zjrb_card' )->field( 'addr_id, customer_id' )->where( $condition )->find();
        $customer_addr = M( 'zjrb_card' )->where( $condition )->getField( 'addr_id' );
        /*$condition = array( 'id' => $customer_addr['customer_id'], 'scope' => 'zjdailycard' );

        $updated_customer = $this->updateCustomer( $data, $condition );
        if( is_string( $updated_customer ) ){
            return $this->error( $updated_customer );
        }else if( $updated_customer === false ){
            return $this->error( "卡片相关用户信息更新失败" );
        }*/

        $condition = array( 'id' => $customer_addr, 'scope' => 'zjdailycard' );
        $updated_addr = $this->updateCustomerAddr( $data, $condition );

        if( is_string( $updated_addr ) ){
            return $this->error( $updated_addr );
        }else if( $updated_addr === false ){
            // return $this->error( "卡片相关地址信息更新失败" );
            return $this->error( "更新失败" );
        }

        $this->success( "更新成功" );
    }


    /**
     * (批量)生成浙江日报报卡数据
     */
	public function generate()
	{
        if( IS_GET ){
            $cardEncryption = array( array( "id" => 1, 'name' => '纯数字' ), array( 'id' => 2, 'name' => '字母＋数字' ), array( 'id' => 3, 'name' => '小写字母＋数字' ), array( 'id' => 4, 'name' => '大写字母＋数字' ) );
            $this->assign( "cardEncry", $cardEncryption );
            $this->display();
            return;
        }

        $condition['count'] = I( "post.count", 0, "" );
        $condition['base_on_year'] = I( "post.base_on_year", "", "" );
        $condition['base_on_increment'] = I( "post.base_on_increment", 1, "" );
        $condition['use_password_type'] = I( "post.card_encry", 1, "" );//1: numbers, 2: numbers + alph( lowcase ), 3: numbers + alph ( upcase ), 4: numbers + alph( both lowcase and upcase )
        $condition['begintime'] = I( "post.begin_time", "", "" );
        $condition['endtime'] = I( "post.end_time", "", "" );

        $result = array( "err" => 400, 'msg' => '生成错误' );
        if( !$condition['count'] ){
            $result['err'] = 400;
            $result['msg'] = '报卡生成数量不能为0';
            $this->ajaxReturn( $result );
        }

        if( empty( $condition['begintime'] ) || empty( $condition['endtime'] ) ){
            $result['err'] = 400;
            $result['msg'] = '报卡有效时间不能为空';
            $this->ajaxReturn( $result );
        }

        trace( array( strtotime( $condition['begintime'] ) ), '', 'INFO' );
        if( strtotime( $condition['begintime'] ) > strtotime( $condition['endtime'] ) ){
            $result['err'] = 400;
            $result['msg'] = '报卡有效日期不正确';
            $this->ajaxReturn( $result );
        }

        $generated = A( "ZJDailyCard", "Logic" )->generate( $condition );
        if( $generated === 0 ){
            $result['err'] = 403;
            $result['msg'] = '生成失败';
        }else if( $generated ){
            $result['err'] = 200;
            $result['msg'] = '生成成功';
        }
        $this->ajaxReturn( $result );
	}


    public function download()
    {
        $options = I( "post.file", 'excel', "" );
        $items = I( "post.items", array(), "" );
        $condition['status'] = I( "post.status", "", "" );
        $condition['distributionyear'] = I( "post.distributionyear", "", "" );

        /*if( empty( $condition['status'] ) ){
            $condition['status'] = array( "gt", -1 );
        }*/
        if( $condition['status'] == 3 ){
            $condition['status'] = array( 'gt', 0 );
        }
        if( count( $items ) ){
            $condition["esm_zjrb_card.id"] = array( "in", $items );
        }/*else{
            $items = array( -1 );
            $condition['esm_zjrb_card.id'] = array( "in", $items );
        }*/

        $en_fields = array(
            "esm_zjrb_card.id" => 'cardid',
            "esm_zjrb_card.cardnumber" => 'cardnumber',
            "esm_zjrb_card.password" => 'password',
            "esm_zjrb_card.status" => 'status',
            // "customer.username" => 'customer',
            // "customer.telephone" => 'contact',
            "address.username" => 'name',
            "address.telephone" => 'telephone',
            // "province.regionname" => 'province',
            "city.regionname" => 'city',
            "county.regionname" => 'county',
            "address.address" => 'address',
            "esm_zjrb_card.signtime" => 'signtime',
            // "esm_zjrb_card.begintime" => 'begintime',
            // "esm_zjrb_card.endtime" => 'endtime',
            "esm_zjrb_card.distributionyear" => 'distributionyear',
        );
        $zh_fields = array(
            "编号",
            "卡号",
            "激活码",
            "激活状态",
            // "注册用户",
            // "注册号码",
            "客户姓名",
            "客户电话",
            // "省",
            "市",
            "区",
            "详细地址",
            "激活时间",
            // "开始时间",
            // "结束时间",
            "发行年份"
        );

        // $condition['status'] = array( 'gt', -2 );
        $datas = M( "zjrb_card" )
            // ->join( 'LEFT JOIN esm_zjdailycard_customer as customer ON customer.id = esm_zjrb_card.customer_id' )
            ->join( 'LEFT JOIN esm_customer_addr as address ON address.id = esm_zjrb_card.addr_id' )
            ->join( 'LEFT JOIN esm_region as province ON province.id = address.province' )
            ->join( 'LEFT JOIN esm_region as city ON city.id = address.city' )
            ->join( 'LEFT JOIN esm_region as county ON county.id = address.county' )
            ->field( $en_fields )
            ->where( $condition )
            ->select();

        $condition['status'] = 1;
        $updated = M( 'zjrb_card' )->where( $condition )->setField( 'status', 2 );
        if( $updated === false ){
            $this->error( "导出失败" );
        }

        if( $options === "excel" ){
            $this->exportexcel( $datas, $zh_fields, "浙江日报报卡" );
        }
    }

    public function queryDiffSet()
    {
        $condition['base_on_year'] = I( "post.base_on_year", "", "" );
        $condition['base_on_increment'] = I( "post.base_on_increment", "", "" );

        $result = array( "error" => 500, "msg" => "发生未知错误" );
        if( empty( $condition['base_on_year'] ) || empty( $condition['base_on_increment'] ) ){
            $this->ajaxReturn( $result );
        }
        $result['data'] = A( "ZJDailyCard", "Logic" )->queryDiffSet( $condition );


        trace( $result, 'debug' );
        if( $result['data'] === -1 ){
            $result['error'] = 200;
            $result['data'] = $condition['base_on_increment'];
            $result['msg'] = "没有发生错误";
        }else if( $result['data'] > 0){
            $result['error'] = 200;
            $result['msg'] = "没有发生错误";
        }

        trace( $result, 'debug' );

        $this->ajaxReturn( $result );
    }

    private function exportexcel($data=array(),$title=array(),$filename='report'){
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)){
            foreach ($title as $k => $v) {
                $title[$k]=iconv("UTF-8", "GB2312",$v);
            }
            $title= implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)){
            foreach($data as $key=>$val){
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck]=iconv("UTF-8", "GB2312", "\"".$cv."\"");
                }
                $data[$key]=implode("\t", $data[$key]);
            }
            echo implode("\n",$data);
        }
    }

    private function updateCustomer( $data, $condition )
    {
        $rules = array(
            array( 'username', '/^[a-zA-Zxa0-xff_][0-9a-zA-Zxa0-xff_]{3,15}$/', '姓名不能出现特殊字符', 'regex' ),
            array( 'telephone', '/^1[0-9]{10}$/', '手机号码格式不正确', 'regex' ),
            // array( 'metier', '/^[a-zA-Zxa0-xff_][0-9a-zA-Zxa0-xff_]{3,15}$/', '职业描述不能出现特殊字符', 'regex' )
        );
        $exclude = array( 'id' => '', 'username' => '', 'telephone' => '', 'metier' => ''  );
        $data = array_diff_key( $data, $exclude );
        $mode = M( 'zjdailycard_customer' );
        $validated = $mode->validate( $rules )->create( $data );
        if( !$validated ){
            return $mode->getError();
        }

        return $mode->where( $condition )->save( $data );
    }

    private function updateCustomerAddr( $data, $condition )
    {
        $rules = array(
            array( 'province', 'require', '省不能为空' ),
            array( 'city', 'require', '市不能为空' ),
            array( 'county', 'require', '区不能为空' ),
            array( 'address', 'require', '地址不能为空' ),
            array( 'username', 'require', '姓名不能为空' ),
            array( 'username', '/^[\x{4E00}-\x{9FA5}]+$/u', '姓名需为2-20位中文', 1, 'regex' ),
            // array( 'username', 'len', '姓名需为2-20位中文', 1, 'callback', 1, array( array( "min" => 2, "max" => 20 ) ) ),
            array( 'metier', 'require', '职业不能为空' ),
            array( 'telephone', '/(^1\d{10}$)/', '手机号码格式不正确', 1, 'regex' )
            //array( 'province', 'requireExistProvince', '省不存在', 1, 'function' ),
            //array( 'city', 'requireExistCity', '省、市不匹配', 'function', $data ),
            //array( 'county', 'requireExistCounty', '市、区不匹配', 'function', $data ),
            //array( 'address', '', '' )
        );
        $exclude = array(
            'id' => '',
            // 'city' => '',
            // 'county' => '',
            // 'address' => ''
        );
        $data = array_diff_key( $data, $exclude );
        $mode = M( 'customer_addr' );
        $validated = $mode->validate( $rules )->create( $data );
        if( !$validated ){
             return $mode->getError();
        }
        //TODO: not good
        if( !$this->len( $data['username'], array( "min" => 2, "max" => 20 ) ) ){
            return "姓名需为2-20位中文";
        }
        return $mode->where( $condition )->save( $data );
    }

    private function updateZJDailyCard( $data, $condition )
    {
        $rules = array(
            //array( "begintime", "" ),
            //array( "endtime", "" ),
            //array( "signtime", "" ),
            array( "status", array( -2, -1, 0, 1, 2 ), "状态值非法", "in" ),
            //array( "distributionyear", "" )
        );
        $exclude = array(
            'id' => '',
            'customer_id',
            'addr_id',
            'cardnumber',
            'password',
            'begintime',
            'endtime',
            'signtime',
            'status',
            'distributionyear'
        );

        $data = array_diff_key( $data, $exclude );
        $mode = M( 'zjrb_card' );
        $validated = $mode->validate( $rules )->create( $data );
        if( !$validated ){
             return $mode->getError();
        }
        return $mode->where( $condition )->save( $data );
    }

    private function requireExistProvince( $province )
    {
        return false;
        $condition['id'] = $province;
        $founed = M( 'region' )->where( $condition )->find();
        if( $founed ){
             return true;
        }else{
            return false;
        }
    }

    private function requireExistCity( $city, $_data )
    {
        $condition['parentid'] = $_data['province'];
        $condition['id'] = $city;
        $founed = M( 'region' )->where( $condition )->find();
        if( $founed ){
             return true;
        }else{
            return false;
        }
    }

    private function requireExistCounty( $county, $_data )
    {
        //$condition['province'] = $_data['province'];
        $condition['parentid'] = $_data['city'];
        $condition['id'] = $_data['county'];
        $founed = M( 'region' )->where( $condition )->find();
        if( $founed ){
             return true;
        }else{
            return false;
        }
    }

    public function len( $str, $condition )
    {
        $minRequire = true;
        $maxRequire = true;
        trace( $condition, "len", "INFO" );
        trace( $str, "len str", "INFO" );
        if( isset( $condition['min'] ) ){
            $minRequire = mb_strlen($str, 'utf-8') >= $condition['min'] ? true : false;
        }
        if( isset( $condition['max'] ) ){
            $maxRequire = mb_strlen($str, 'utf-8') <= $condition['max'] ? true : false;
        }
        return ($minRequire && $maxRequire);
    }
}

?>
